package org.hfy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hfy.dto.OptionDTO;
import org.hfy.dto.OutsourcingQueryDTO;
import org.hfy.entity.Outsourcing;
import org.hfy.entity.Quotation;
import org.hfy.enums.OutsourcingStatus;
import org.hfy.enums.QuotationStatus;
import org.hfy.mapper.OutsourcingMapper;
import org.hfy.service.OutsourcingService;
import org.hfy.service.QuotationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 外发加工服务实现类
 * 
 * @author hfy
 * @version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OutsourcingServiceImpl extends ServiceImpl<OutsourcingMapper, Outsourcing> implements OutsourcingService {

    private final QuotationService quotationService;

    @Override
    public IPage<Outsourcing> getOutsourcingPage(OutsourcingQueryDTO query) {
        Page<Outsourcing> page = new Page<>(query.getCurrent(), query.getSize());
        return baseMapper.selectOutsourcingPage(page, query);
    }

    @Override
    public Outsourcing getOutsourcingWithDetailsById(Long id) {
        return baseMapper.selectOutsourcingWithDetailsById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Outsourcing createOutsourcing(Outsourcing outsourcing) {
        // 检查报价单状态
        if (outsourcing.getQuotationId() != null) {
            Quotation quotation = quotationService.getById(outsourcing.getQuotationId());
            if (quotation != null) {
                QuotationStatus currentStatus = QuotationStatus.fromCode(quotation.getStatus());
                if (!currentStatus.canOutsource()) {
                    throw new RuntimeException("当前报价单状态不允许外发加工，只有合同审核通过、外发加工中或已入库的报价单才能外发加工");
                }
                
                // 如果是合同审核通过状态，更新为外发加工中；如果已经是外发加工中或已入库状态，则保持不变
                if (currentStatus == QuotationStatus.CONTRACT_APPROVED) {
                    quotationService.updateStatusToOutsourcing(outsourcing.getQuotationId());
                    log.info("已更新报价单状态为外发加工中，报价单ID: {}", outsourcing.getQuotationId());
                } else {
                    log.info("报价单已处于外发加工状态，无需更新状态，报价单ID: {}", outsourcing.getQuotationId());
                }
            }
        }
        
        // 生成外发单号
        if (!StringUtils.hasText(outsourcing.getOutsourcingNo())) {
            outsourcing.setOutsourcingNo(generateOutsourcingNo());
        }
        
        // 设置默认状态
        if (!StringUtils.hasText(outsourcing.getStatus())) {
            outsourcing.setStatus(OutsourcingStatus.OUTSOURCED.getCode());
        }
        
        // 计算总金额
        if (outsourcing.getUnitPrice() != null && outsourcing.getQuantity() != null) {
            outsourcing.setTotalAmount(
                outsourcing.getUnitPrice().multiply(java.math.BigDecimal.valueOf(outsourcing.getQuantity()))
            );
        }
        
        save(outsourcing);
        return outsourcing;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOutsourcingStatus(Long id, String status, LocalDate actualReturnDate) {
        Outsourcing outsourcing = getById(id);
        if (outsourcing == null) {
            throw new RuntimeException("外发单不存在");
        }
        
        outsourcing.setStatus(status);
        if (actualReturnDate != null) {
            outsourcing.setActualReturnDate(actualReturnDate);
        }
        
        return updateById(outsourcing);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOutsourcing(Long id) {
        return removeById(id);
    }

    @Override
    public List<OptionDTO> getSupplierOptions() {
        // TODO: 从供应商管理模块获取供应商列表
        // 这里先返回模拟数据，实际应该调用供应商服务接口
        return Arrays.asList(
            new OptionDTO("S001", "供应商A"),
            new OptionDTO("S002", "供应商B"),
            new OptionDTO("S003", "供应商C")
        );
    }

    @Override
    public String generateOutsourcingNo() {
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String prefix = "WF" + dateStr;
        
        try {
            // 查询当日已有的外发单数量
            LambdaQueryWrapper<Outsourcing> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.likeRight(Outsourcing::getOutsourcingNo, prefix)
                       .eq(Outsourcing::getDeleted, 0);
            long count = count(queryWrapper);
            
            // 序号从1开始，格式化为4位数字
            int sequence = (int) (count + 1);
            return prefix + String.format("%04d", sequence);
            
        } catch (Exception e) {
            log.error("生成外发单号失败，使用默认序号", e);
            // 如果查询失败，使用时间戳后4位作为序号
        int sequence = (int) (System.currentTimeMillis() % 10000);
        return prefix + String.format("%04d", sequence);
        }
    }

    @Override
    public List<Quotation> getAvailableQuotationsForOutsourcing() {
        // 查询状态为"合同审核通过"、"外发加工中"或"已入库"的报价单
        return quotationService.getQuotationsByStatus(
            Arrays.asList(
                QuotationStatus.CONTRACT_APPROVED.getCode(),
                QuotationStatus.OUTSOURCING.getCode(),
                QuotationStatus.WAREHOUSED.getCode()
            )
        );
    }
} 